package com.finance.console.service.report;

import com.finance.console.entity.StatResult;
import com.finance.console.service.statisticc.FinancialStatService; // 修复包名错误
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class ReportService {
    private final FinancialStatService statService = new FinancialStatService();

    // 生成月度财务报表（文本文件）
    public void generateMonthReport(int userId, String yearMonth, String savePath) {
        try {
            // 1. 获取统计数据
            StatResult stat = statService.statMonth(userId, yearMonth);

            // 2. 生成报表内容
            StringBuilder report = new StringBuilder();
            report.append("===== " + yearMonth + " 财务报表 =====\n\n");
            report.append("1. 收支概览\n");
            report.append("   总收入：" + stat.getTotalIncome() + " 元\n");
            report.append("   总支出：" + stat.getTotalExpense() + " 元\n");
            report.append("   月结余：" + stat.getBalance() + " 元\n\n");
            report.append("2. 支出明细（按类型）\n");
            // 修复方法名错误：getTypeExpense() -> getCategoryExpense()
            stat.getCategoryExpense().forEach((type, amount) ->
                    report.append("   " + type + "：" + amount + " 元\n")
            );
            report.append("\n===== 报表生成时间：" + new java.util.Date() + " =====");

            // 3. 保存到文件
            // 确保目录存在
            File dir = new File(savePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, "finance_report_" + yearMonth + ".txt");
            try (FileWriter writer = new FileWriter(file)) {
                writer.write(report.toString());
            }
            System.out.println("报表生成成功，保存路径：" + file.getAbsolutePath());
        } catch (Exception e) { // 捕获FinanceException
            throw new RuntimeException("报表生成失败：" + e.getMessage());
        }
    }
}